package lsp.decoder;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import lsp.base.LspParams;
import lsp.client.LspClient;
import util.HashUtil;
import util.SleepUtil;
import util.StringUtil;

public class Worker {
	
	private LspClient lspClient;
	
	public Worker(String serverHost, int port) throws IOException {
		lspClient = new LspClient(serverHost, port, new LspParams(5000, 5));
		
		joinRequest();
	}

	private void joinRequest() {
		lspClient.write("J".getBytes());
	}
	
	public void execute() throws NoSuchAlgorithmException {
		while (true) {
			String message = new String(lspClient.read());
			
			if (message.startsWith("C")) {
				String password = crackPassword(message);
				sendResponseToServer(password);
			}
			
			SleepUtil.rest(20);
		}
	}

	private void sendResponseToServer(String password) {
		if (password == null) {
			lspClient.write("X".getBytes());
		} else {
			lspClient.write(("F " + password).getBytes());
		}
	}

	private String crackPassword(String message) throws NoSuchAlgorithmException {
		String[] messageElements = message.split(" ");
		String hash = messageElements[1];
		int lower = Integer.valueOf(messageElements[2]);
		int upper = Integer.valueOf(messageElements[3]);
		
		return crackPassword(hash, lower, upper);
	}

	private String crackPassword(String hash, int lower, int upper) throws NoSuchAlgorithmException {
		for (int i = lower; i <= upper; i++) {
			String value = StringUtil.padRight(String.valueOf(i), '0', 4);
			if (HashUtil.hashSHA1(value).equals(hash)) {
				return value;
			}
		}
		return null;
	}
	
}
